from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import PermissionDenied
from django.contrib.auth.models import Permission


class RoleAuthenticationBackend(ModelBackend):

    def _get_role_permissions(self, user_obj):
        tenant = getattr(user_obj, 'tenant', None)
        if not tenant:
            raise PermissionDenied

        return Permission.objects.filter(role__user=user_obj, role__tenant=tenant)

    def has_perm(self, user_obj, perm, obj=None):
        return perm in self._get_permissions(user_obj, obj, 'role')
